package com.bhs.sansonglogistics.ui.wallet;


import android.annotation.SuppressLint;
import android.content.Intent;
import android.util.ArrayMap;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.bhs.sansonglogistics.R;
import com.bhs.sansonglogistics.base.BaseActivity;
import com.bhs.sansonglogistics.base.BaseBean;
import com.bhs.sansonglogistics.base.Constants;
import com.bhs.sansonglogistics.bean.AdvancePayment;
import com.bhs.sansonglogistics.bean.PayInfo;
import com.bhs.sansonglogistics.bean.PayInfo2;
import com.bhs.sansonglogistics.bean.UserInfoBean;
import com.bhs.sansonglogistics.bean.event.PayStatus;
import com.bhs.sansonglogistics.net.NetCallBack;
import com.bhs.sansonglogistics.ui.order.OrderDetailsActivity;
import com.bhs.sansonglogistics.utils.FastCilckOneUtil;
import com.bhs.sansonglogistics.utils.PayUtils;
import com.bhs.sansonglogistics.utils.ToastUtil;
import com.google.gson.Gson;
import com.tencent.mm.opensdk.modelbase.BaseResp;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;

import java.util.Map;

import okhttp3.ResponseBody;
import retrofit2.Response;

/**
 * 收银台
 */
public class PayDeskActivity extends BaseActivity implements View.OnClickListener, NetCallBack {
    private TextView mTvTitle;
    private int payType = 1;//1=零钱，2=微信小程序，3=微信app
    private int tradingHour = 15;//交易倒计时 分钟
    private LinearLayout mLlPayDesk;
    private LinearLayout mLlPaymentSuccess;
    private TextView mTvTradingHour;
    private TextView mTvMoney;
    private TextView mTvBalance;
    private ImageView mIvBalancePay;
    private TextView mTvBankCard;
    private ImageView mIvBankCardPay;
    private ImageView mIvAlipay;
    private ImageView mIvWeChat;
    private CheckBox mCbRedPacket;
    private Button mBtnSubmit;
    private Button mBtnBack;
    private String paySn;
    private TextView mTvPaySn;
    private Button mBtnCheckOrder;
    private String deliver_sn;
    private IWXAPI msgApi;
    private int type;//1品质专线  2专线推广 3会员专线 4异常单支付 12续费专线推广 13续费专线会员
    private String redEnvelopeDeduction;

    @Override
    public int initLayout() {
        return R.layout.activity_pay_desk;
    }

    @Override
    public void initView() {
        //注册监听
        EventBus.getDefault().register(this);
        paySn = getIntent().getStringExtra("pay_sn");
        type = getIntent().getIntExtra("type", 1);
        mTvTitle = findViewById(R.id.tv_title);
        mTvTitle.setText("结算");
        mLlPaymentSuccess = findViewById(R.id.ll_payment_success);
        mLlPayDesk = findViewById(R.id.ll_pay_desk);
        mTvTradingHour = findViewById(R.id.tv_trading_hour);
        mTvMoney = findViewById(R.id.tv_money);
        mTvBalance = findViewById(R.id.tv_balance);
        mIvBalancePay = findViewById(R.id.iv_balance_pay);
        mTvBankCard = findViewById(R.id.tv_bank_card);
        mIvBankCardPay = findViewById(R.id.iv_bank_card_pay);
        mIvAlipay = findViewById(R.id.iv_alipay);
        mIvWeChat = findViewById(R.id.iv_we_chat);
        mCbRedPacket = findViewById(R.id.cb_red_packet);
        mBtnSubmit = findViewById(R.id.btn_submit);
        mBtnBack = findViewById(R.id.btn_back);
        mBtnBack.setOnClickListener(this);
        mBtnSubmit.setOnClickListener(this);
        findViewById(R.id.ll_we_chat).setOnClickListener(this);
        findViewById(R.id.ll_alipay).setOnClickListener(this);
        findViewById(R.id.ll_bank_card).setOnClickListener(this);
        findViewById(R.id.ll_balance).setOnClickListener(this);
        mTvPaySn = findViewById(R.id.tv_pay_sn);
        mBtnCheckOrder = findViewById(R.id.btn_check_order);
        mBtnCheckOrder.setOnClickListener(this);
        msgApi = WXAPIFactory.createWXAPI(mActivity, null);
        // 将该app注册到微信
        msgApi.registerApp(Constants.APP_ID);
    }

    @Override
    public void initData() {
        networkRequest(netApi.get_user_info(), this, 9527);
        mTvPaySn.setText(String.format("伞送科技-%s", paySn));
        mTvMoney.setText(getIntent().getStringExtra("money"));
        if (type == 2 || type == 12) {
            networkRequest(netApi.get_promote_redpack_info(getIntent().getStringExtra("promote_type")), this, 999);
        }
    }

    @SuppressLint("NonConstantResourceId")
    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.ll_we_chat:
                payType = 3;
                setChecked(mIvWeChat);
                break;
            case R.id.ll_alipay:
                payType = 4;
                setChecked(mIvAlipay);
                break;
            case R.id.ll_balance:
                payType = 1;
                setChecked(mIvBalancePay);
                break;
            case R.id.btn_submit:
                submit();
                break;
            case R.id.btn_back:
                finish();
                break;
            case R.id.btn_check_order:
                startActivity(new Intent(mActivity, OrderDetailsActivity.class).putExtra("deliver_sn", deliver_sn));
                finish();
                break;
        }
    }

    private void submit() {
        if (FastCilckOneUtil.isFastClick()) {
            return;
        }
        Map<String, String> map = new ArrayMap<>();
        map.put("order_id", paySn);
        map.put("pay_method", String.valueOf(payType));//支付方式 4微信支付
        if (type == 1) {
            networkRequest(netApi.pay_deposit_order(map), this, 888);
        } else if (type == 2) {
            if (mCbRedPacket.isChecked()) {
                map.put("redpack_money", redEnvelopeDeduction);
            } else {
                map.put("redpack_money", "0");
            }
            networkRequest(netApi.pay_promote_order(map), this, 888);
        } else if (type == 3) {
            networkRequest(netApi.pay_member_order(map), this, 888);
        } else if (type == 4) {
            networkRequest(netApi.pay_abnormal_order(map), this, 888);
        } else if (type == 13) {
            networkRequest(netApi.pay_renew_member_order(map), this, 888);
        } else if (type == 12) {
            if (mCbRedPacket.isChecked()) {
                map.put("redpack_money", redEnvelopeDeduction);
            } else {
                map.put("redpack_money", "0");
            }
            networkRequest(netApi.pay_renew_promote_order(map), this, 888);
        }
    }


    private void setChecked(ImageView imageView) {
        mIvAlipay.setImageResource(R.mipmap.ic_unchecked);
        mIvBalancePay.setImageResource(R.mipmap.ic_unchecked);
        mIvWeChat.setImageResource(R.mipmap.ic_unchecked);
        mIvBankCardPay.setImageResource(R.mipmap.ic_unchecked);
        imageView.setImageResource(R.mipmap.ic_checked);
    }

    @Override
    public void onResponse(int requestCode, String json, Response<ResponseBody> response) throws Exception {
        if (requestCode == 9527) {
            UserInfoBean userInfo = new Gson().fromJson(json, UserInfoBean.class);
            if (userInfo.isStatus()) {
                mTvBalance.setText(String.format("可用余额%s元", userInfo.getData().getLogistics_info().getMoney01()));
            }
        } else if (requestCode == 888) {
            PayInfo2 bean = new Gson().fromJson(json, PayInfo2.class);
            if (bean.isStatus()) {
                if (payType == 1) {
                    EventBus.getDefault().post(new PayStatus());
                    mLlPaymentSuccess.setVisibility(View.VISIBLE);
                    mLlPayDesk.setVisibility(View.GONE);
                } else {
                    PayUtils.weChatPay(mContext, bean.getData(), msgApi);
                }
            } else {
                ToastUtil.show(bean.getMsg());
            }
        } else if (requestCode == 999) {
            AdvancePayment bean = new Gson().fromJson(json, AdvancePayment.class);
            if (bean.isStatus()) {
                mCbRedPacket.setVisibility(View.VISIBLE);
                redEnvelopeDeduction = bean.getData().getNum();
                mCbRedPacket.setText(String.format("红包可抵扣金额：%s元", bean.getData().getNum()));
            }
        }
    }

    @Subscribe
    public void onEvent(BaseResp event) {
        if (event.errCode == BaseResp.ErrCode.ERR_OK) {
            EventBus.getDefault().post(new PayStatus());
            mLlPaymentSuccess.setVisibility(View.VISIBLE);
            mLlPayDesk.setVisibility(View.GONE);
        }
    }


    @Override
    public void onFailure(int requestCode) {

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

    @Override
    public void onBackPressed() {
        Intent i = new Intent();
        setResult(1, i);
        finish();
    }
}